package com.cuitrip.business.tripservice;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cuitrip.apiservice.CommonBusiness;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.presenter.TripEditPresenter;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.service.R;
import com.cuitrip.util.ImageFetcherManager;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.photopicker.DefaultCallback;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.ArrayUtil;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.utils.imageupload.URLImageParser;
import com.lab.utils.imageupload.imp.OssService;
import com.lab.utils.imageupload.model.OssTokenObject;
import com.lab.widget.PicTextEditView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 图文混排
 * Created on 7/23.
 */
public class TripDescriptionActivity extends CustomUiFragmentActivity implements IProxyCallback {

    public static final String EDIT_MODE = "edit_mode";
    public static final String LOCAL_SERVICE = "local_saved_service";
    public static final String BACK_PIC_KEY = "back_pic";
    public static final String PIC_LIST_KEY = "pic_list";
    public static final String DESC_KEY = "desc";
    private static final String TAG = "CreateServiceActivity";
    private static final int REQUEST_IMAGE = 99;
    private static final int REQUEST_PHOTO = 100;
    private static final int MAX_IMAGE_COUNT = 9;
    private static final int MAX_TEXT_COUNT = 7500;
    @Bind(R.id.image_count)
    protected TextView imageCountView;
    @Bind(R.id.text_count)
    protected TextView textCountView;
    @Bind(R.id.service_content)
    PicTextEditView mPicEditTextView;
    @Bind(R.id.service_desc_scroll)
    ScrollView mDescriptionLayout;
    //  private PicTextEditView mPicEditTextView;
    private ServiceInfo mServiceInfo;
    private boolean mInEdit;
    private OssService ossService = new OssService();

    private ApiProxy mApiProxy = new ApiProxy(this);

    private Animation shakeAnimation;

    private ImageFetcherManager mImageFetcherManager = new ImageFetcherManager(this, ImageFetcherManager.Source.CREATE_SERVICE);

    public static void startModifyRemote(Activity context, ServiceInfo serviceInfo) {
        Intent intent = new Intent(context, TripDescriptionActivity.class);
        intent.putExtra(ServiceInfo.KEY, serviceInfo)
                .putExtra(TripDescriptionActivity.EDIT_MODE, true);
        Jumper.launchActivityForResult(context, intent, TripEditPresenter.DESCRIPTION_TYPE);
    }

    @OnClick(R.id.choose_image_action)
    public void chooseImage() {
        mPicEditTextView.addImage();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent != null && (mInEdit = intent.getBooleanExtra(EDIT_MODE, false))) {
            mServiceInfo = (ServiceInfo) intent.getSerializableExtra(ServiceInfo.KEY);
            if (mServiceInfo == null) {
                finish();
                return;
            }
        }
        super.onCreate(savedInstanceState, R.layout.page_trip_description);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.shake);
        mPicEditTextView.setActivity(this);
        if (mInEdit) {
            mPicEditTextView.initDesc(URLImageParser.replae(mServiceInfo.getServiceDescript()), mServiceInfo.getBackPic(), mServiceInfo.getPic());
        } else {
            mPicEditTextView.initDesc("", null, null);
        }
        updateTextCount(mPicEditTextView.textCount());
        updateImageCount(mPicEditTextView.pictureCount());
        mPicEditTextView.setmContentChangeCallBack(new PicTextEditView.ContentChangeCallBack() {
            @Override
            public void onImageCountChanged(int imageCount) {
                updateImageCount(imageCount);
            }

            @Override
            public void onTextCountChanged(int textCount) {
                updateTextCount(textCount);
            }
        });
    }

    private void updateImageCount(int imageCount) {
        imageCountView.setText(imageCount + "/" + MAX_IMAGE_COUNT);
    }

    private void updateTextCount(int textCount) {
        textCountView.setText(textCount + "/" + MAX_TEXT_COUNT);
    }

    @Override
    public void initData() {
        requestImageToken();
    }

    public void requestImageToken() {
        CommonBusiness.getMobileOssToken(mApiProxy);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.ct_menu_save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:
                saveAction();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void saveAction() {
        if (mPicEditTextView.isUpdating()) {
            MessageUtils.showToast(getString(R.string.operation_upload_photo_state));
            return;
        }
        String content = mPicEditTextView.generateDesc();
        if (TextUtils.isEmpty(content)) {
            mDescriptionLayout.startAnimation(shakeAnimation);
            return;
        }
        if ((content == null || TextUtils.isEmpty(content.trim()) && !mInEdit)) {
            return;
        }
        if (ArrayUtil.isNullOrEmpty(mPicEditTextView.getPictures())) {
            MessageUtils.showToast(R.string.operation_upload_photo_limit_3);
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(DESC_KEY, content);
        intent.putStringArrayListExtra(PIC_LIST_KEY, mPicEditTextView.getPictures());
        mPicEditTextView.deletePictures();
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
                //Some error handling
            }

            @Override
            public void onImagePicked(final File imageFile, EasyImage.ImageSource source) {
                //Handle the image
                if (null != imageFile && !TextUtils.isEmpty(imageFile.getAbsolutePath())) {
                    int imageFileSize = ImageFetcherManager.calcImageFileSize(imageFile);
                    AppLog.d(TAG + " onActivityResult REQUEST_CODE_PICK_IMAGE imageFileSize = " + imageFileSize);
                    ImageLoader.getInstance().loadImage(Uri.fromFile(imageFile).toString(), new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
                            mPicEditTextView.insertImage(loadedImage, imageFile);
                        }
                    });
                }

            }

            @Override
            public void onCanceled(EasyImage.ImageSource source) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(AppCoreRuntime.context);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }

    public void onBackPressed() {
        final String desc = mPicEditTextView.generateDesc();
        if ((desc == null || TextUtils.isEmpty(desc.trim())) && !mInEdit) {
            super.onBackPressed();
            return;
        }

        final ChoiceDialog dialog = new ChoiceDialog();
        dialog.setDialogMessage(getString(R.string.operation_cancel_confrim));
        dialog.setDialogTitleDividerVisibility(false);
        dialog.setDialogTitleVisibility(false);
        dialog.setDialogCoupleStyleSetting(getString(R.string.operation_yes), getString(R.string.operation_cancel), new ChoiceDialog.DialogStyleCoupleCallback() {
            @Override
            public boolean onPositiveButtonClick() {
                finish();
                return true;
            }

            @Override
            public boolean onNegativeButtonClick() {
                hideDialogFragment(dialog);
                return true;
            }
        });
        showDialogFragment(dialog);
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getString(R.string.trip_attribute_description);
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarRightAreaName = getString(R.string.operation_save);
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }

    @Override
    public void onTopbarRightPress() {
        saveAction();
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response.isResponseNormal()) {
            OssTokenObject ossTokenObject = (OssTokenObject) response.result;
            ossService.initClient(ossTokenObject);
            mPicEditTextView.setOssService(ossService);
            mPicEditTextView.setUid(LoginInstance.getInstance().getUserInfo().getUid());
        } else {
            if (!TextUtils.isEmpty(response.msg)) {
                ToastUtil.toast(response.msg);
            }
        }
        return false;
    }
}
